import 'dart:async';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  int _count = 0;
  Timer? _timer;
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _timer!.cancel(); // 注意清除定时器
    super.dispose();
  }

  _getCode() async {
    if (_count > 0) {
      return;
    }
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(_phoneController.text)) {
      return ToastUtil.showError('手机号格式不正确');
    }
    _countDownTime();
    final res =
        await http.get('/code', params: {'mobile': _phoneController.text});
    _codeController.text = res['data']['code'];
  }

  _login() async {
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(_phoneController.text)) {
      return ToastUtil.showError('手机号格式不正确');
    }
    if (!RegExp(r'^\d{6}$').hasMatch(_codeController.text)) {
      return ToastUtil.showError('验证码格式不正确');
    }
    final res = await http.post('/login',
        {'mobile': _phoneController.text, 'code': _codeController.text});
    if (res['code'] != 10000) return ToastUtil.showError('登录失败');
    // 3.4 存储token
    TokenManager().saveToken(res['data']['token']);
    ToastUtil.showSuccess('登录成功');
    eventBus.fire(RefreshInfo());
    // 3.5 返回到上一页
    Navigator.pop(context);
  }

  _countDownTime() {
    if (_count > 0) {
      return;
    }
    setState(() {
      _count = 5;
    });
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _count--;
        if (_count <= 0) {
          timer.cancel();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Row(
                children: [
                  Text('登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold))
                ],
              ),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))
                ],
              ),
              const SizedBox(height: 30),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: TextField(
                      controller: _phoneController,
                      decoration: const InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入手机号',
                      ),
                    ),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shadowColor: Colors.transparent,
                      foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _getCode();
                    },
                    child: _count > 0
                        ? Text('$_count秒后重新获取')
                        : const Text('获取验证码'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                controller: _codeController,
                decoration: const InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
              ),
              const SizedBox(height: 8),
              const Row(children: [
                Text('未注册手机号经验证后将自动登录',
                    style: TextStyle(fontSize: 12, color: Colors.grey)),
              ]),
              const SizedBox(height: 50),
              Row(children: [
                Expanded(
                    child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _login();
                  },
                  child: const Text('登录',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                ))
              ])
            ])));
  }
}
